<template>
	<div class="dishesIndex">
		<el-row :gutter="20">
			<el-col :span="16">
				<el-input v-model="name" size="large" placeholder="请输入菜品名称" :prefix-icon="Search" @keyup.enter="getTableData"
					style="width: 30%" />
			</el-col>

			<el-col :span="8" class="rightCol">
				<el-button type="danger" text
					@click="deleteDish(multipleSelection.map(item => item.id) as string[])">批量删除</el-button>
				<el-button type="primary" text
					@click="batchUpdateStatus(multipleSelection.map(item => item.id) as string[], 1)">批量启售</el-button>
				<el-button type="danger" text
					@click="batchUpdateStatus(multipleSelection.map(item => item.id) as string[], 0)">批量停售</el-button>

				<el-button type="primary" color="#ffb600" :icon="Plus" size="large" @click="showDishesDialog('新增')">
					新增菜品
				</el-button>
			</el-col>
		</el-row>

		<el-table ref="multipleTableRef" :data="tableData" style="width: 100%; margin-top: 20px"
			@selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" />
			<el-table-column prop="name" label="菜品名称" align="center" />

			<el-table-column prop="image" label="图片" align="center">
				<template #default="{ row }">
					<el-image v-if="row.url" style="width: 50px; height: 50px" :src="row.url" :zoom-rate="1.2"
						:preview-src-list="[row.url]" preview-teleported fit="cover" />
				</template>
			</el-table-column>

			<el-table-column prop="categoryName" label="菜品分类" align="center" />
			<el-table-column prop="price" label="售价" align="center" />
			<el-table-column prop="status" label="售卖状态" align="center">
				<template #default="{ row }">{{ row.status === 0 ? '停售' : '起售' }}</template>
			</el-table-column>
			<el-table-column prop="updateTime" label="最后操作时间" align="center" />
			<el-table-column fixed="right" label="操作" width="260" align="center">
				<template #default="{ row }">
					<el-button type="primary" text @click="showDishesDialog('修改', row)">修改</el-button>
					<el-button type="primary" text @click="updateStatus(row)">{{ row.status === 0 ? '起售' : '停售' }}</el-button>
					<el-button type="danger" text @click="deleteDish([row.id])">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40, 50]"
			layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
			@current-change="handleCurrentChange" />

		<DishesDialog v-if="dialogParam.dialogVisible" :dialogParam="dialogParam" @dialogClose="dialogClose" />
	</div>
</template>

<script setup lang="ts" name="dishesIndex">
import { Search, Plus } from '@element-plus/icons-vue'
import { reactive, ref, toRefs, onMounted } from 'vue'
import { SearchType, TableType, DialogType } from './types'
import DishesDialog from './components/DishesDialog.vue'
import { dishPage, downloadImg, updateDish, delDish, batchUpdateStatusApi } from '@/api/index'
import { showLoading, closeLoading } from '@/utils/index'
import { ElMessage } from 'element-plus'

const tableData = ref<TableType[]>([])

const total = ref(0)

const searchParam: SearchType = reactive({
	name: '',
	pageSize: 10,
	pageNum: 1
})

const { name, pageSize, pageNum } = toRefs(searchParam)

const handleSizeChange = (size: number) => {
	searchParam.pageSize = size
	getTableData()
}
const handleCurrentChange = (num: number) => {
	searchParam.pageNum = num
	getTableData()
}

const getTableData = async () => {
	try {
		showLoading()
		const { data } = await dishPage<{ records: TableType[]; total: number }>(searchParam)
		total.value = data.total
		const arr: TableType[] = []

		data.records.forEach(async item => {
			showLoading()
			await getImg(item.image).then(url => {
				item.url = url
				arr.push(item)
			})

			if (arr.length === data.records.length) {
				tableData.value = arr
				closeLoading()
			}
		})
	} catch (error) {
		ElMessage.error(error as string)
		closeLoading()
	}
}

const dialogParam: DialogType = reactive({
	dialogVisible: false,
	title: '',
	id: ''
})

const showDishesDialog = (type: string, row?: TableType) => {
	dialogParam.dialogVisible = true
	dialogParam.title = type

	if (row && row.id) {
		dialogParam.id = row.id
	}
}

const dialogClose = () => {
	dialogParam.dialogVisible = false
	getTableData()
}

const multipleSelection = ref<TableType[]>([])

const handleSelectionChange = (val: TableType[]) => {
	multipleSelection.value = val
}

const getImg = async (url: string) => {
	if (url) {
		try {
			const res = await downloadImg<Blob>({ name: url })
			// 使用 window.URL.createObjectURL 将图片流转为地址
			const path = window.URL.createObjectURL(new Blob([res as any], { type: 'image/png' }))
			return path
		} catch (error) {
			console.log('%c [ error ]-160-「dishesIndex」', 'font-size:13px; background:#232641; color:#676a85;', error)
		}
	}
}

const updateStatus = async (row: TableType) => {
	const params = JSON.parse(JSON.stringify({ ...row }))
	delete params.flavors
	params.flavors = row.flavors && row.flavors.map(item => ({ name: item.name, value: JSON.stringify(item.value) }))
	params.status = params.status === 0 ? 1 : 0
	await updateDish(params)
	ElMessage.success('操作成功')
	getTableData()
}

const batchUpdateStatus = async (ids: string[], status: number) => {
	if (!ids.length) return ElMessage.warning('请选择要删除的菜品')
	try {
		const res = await batchUpdateStatusApi({ ids, status })
		if (res.code === 1) {
			ElMessage.success('操作成功')
			getTableData()
		} else {
			ElMessage.error(res.msg)
		}
	} catch (error) {
		console.log('%c [ error ]-169-「dishesIndex」', 'font-size:13px; background:#29331c; color:#6d7760;', error)
	}
}

const deleteDish = async (ids: string[]) => {
	try {
		const res = await delDish(ids)
		if (res.code === 1) {
			ElMessage.success('删除成功')
			getTableData()
		} else {
			ElMessage.error(res.msg)
		}
	} catch (error) {
		ElMessage.error(error as string)
	}
}

onMounted(() => {
	getTableData()
})
</script>

<style scoped lang="scss">
.dishesIndex {
	height: 100%;
	padding: 10px;
	background-color: #fff;

	.rightCol {
		display: flex;
		justify-content: flex-end;
		align-items: baseline;
	}
}
</style>
